Add protocols SequenceLike and MappingLike#15152
Add protocols SequenceLike and MappingLike#15152srittau wants to merge 4 commits intopython:mainfrom
SequenceLike and MappingLike#15152Conversation
`Sequence` and `Mapping` are commonly used in argument types. This can be problematic, since they are not protocols, making it impossible to safely duck type or mock them. Also, not all sequence- or mapping-like types derive from these ABCs at runtime, although in typeshed we often pretend they do. Ideally we'd be able to avoid this discrepancy in the far future. Finally, the ABCs sometimes make more API promises than their sub-classes fulfill. For example, `Mapping` arguments are keyword-or-positional, while its most important subtype `dict` only accepts positional arguments. These protocols have tighter guarantees. `SequenceLike` contains most, `MappingLike` all methods from their respective types, making them an easy substitute in argument types.
This comment has been minimized.
This comment has been minimized.
|
Why should we use these rather than more precise protocols like |
|
For convenience. I still think using the more precise protocols is the better option in 90% of cases, but sometimes this would be inconvenient, especially as long as we don't have easy protocol composition (via intersections). See also the large amount of |
|
Also, cf. PyCQA/flake8-pyi#525 |
jorenham
left a comment
There was a problem hiding this comment.
Yea this seems useful, and I like the NumPy-esque naming :)
Speaking of NumPy, I left a suggestion that would make np.ndarray assignable to SequenceLike.
This comment has been minimized.
This comment has been minimized.
|
According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉 |
SequenceandMappingare commonly used in argument types. This canbe problematic, since they are not protocols, making it impossible to
safely duck type or mock them. Also, not all sequence- or mapping-like
types derive from these ABCs at runtime, although in typeshed we often
pretend they do. Ideally we'd be able to avoid this discrepancy in the
far future. Finally, the ABCs sometimes make more API promises than
their sub-classes fulfill. For example,
Mappingarguments arekeyword-or-positional, while its most important subtype
dictonlyaccepts positional arguments. These protocols have tighter guarantees.
SequenceLikecontains most,MappingLikeall methods from theirrespective types, making them an easy substitute in argument types.